package com.shop.shoporder.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.shop.shoporder.common.AlipayConfig;
import com.shop.shoporder.common.InterfaceVer;
import com.shop.shoporder.common.MessageConstants;
import com.shop.shoporder.common.Response;
import com.shop.shoporder.entity.order.Order;
import com.shop.shoporder.service.AlipayService;
import com.shop.shoporder.service.OrderService;
import com.shop.shoporder.service.PayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service("alipayService")
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    OrderService orderService;
    @Autowired
    PayOrderService payOrderService;
    @Override
    public Response payAlipay(Map<String, String> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Response responseS=new Response();
        String orderNo="";
        double cash=0;
        try{
            if (map != null) {
                orderNo = map.get("orderNo") == null ? "" : map.get("orderNo");
                cash=InterfaceVer.VerDoubleNumber(map.get("cash") == null ? "" : map.get("cash"));
                AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
                AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
                // 封装请求支付信息
                AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
                int intRandom=(int)(1+Math.random()*(10-1+1)*1000);
                model.setOutTradeNo(orderNo);
//            model.setOutTradeNo("D20190171822"+intRandom);
                model.setSubject("荟品汇享");
                model.setTotalAmount(cash+"");
                model.setBody("荟品汇享");
                model.setTimeoutExpress("lc");
                model.setProductCode("");
                alipay_request.setBizModel(model);
                // 设置异步通知地址
                alipay_request.setNotifyUrl(AlipayConfig.notify_url);
                // 设置同步地址
                alipay_request.setReturnUrl(AlipayConfig.return_url);
                // form表单生产
                String form = "";
                try {int jsonObject= orderService.updatePayType(2,orderNo);}catch (Exception E){}

                try {
                    // 调用SDK生成表单
                    form = client.pageExecute(alipay_request).getBody();
                    response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
                    response.getWriter().write(form);//直接将完整的表单html输出到页面
                    response.getWriter().flush();
                    response.getWriter().close();
                } catch (AlipayApiException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"系统异常！",request);
                }
                return responseS;
            }else {
                return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT,null,0,"参数异常！",request);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"系统异常！",request);
        }
    }

    @Override
    public Response alipayReturn(Map<String, String> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {e.printStackTrace();}
            params.put(name, valueStr);
        }
        String out_trade_no="";
        String cash="";
        try {
            //商户订单号
            out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {e.printStackTrace();}

        try {
            cash = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {e.printStackTrace();}
        try {//支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {e.printStackTrace();}

        //计算得出通知验证结果
        boolean verify_result = false;
        try {
            verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");
        } catch (AlipayApiException e) {e.printStackTrace();}

        if(verify_result){//验证成功
            try {
                Map<String,String> orderParams = new HashMap<String,String>();
                Order order=orderService.selectByOrderNo(out_trade_no);
                if(order!=null){
                    orderParams.put("userNoId",order.getUsernoId()+"");
                    orderParams.put("orderNo",out_trade_no);
                    orderParams.put("inter",order.getInter()+"");
                    orderParams.put("costInter",order.getCostInter()+"");
                    orderParams.put("cash",cash);
                }
                Response response1=payOrderService.payInter(orderParams,request);
                return response1;
            }catch (Exception e){
                return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"支付异常！",request);
            }
        }else{
            return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"支付参数异常！",request);
        }
    }

    @Override
    public Response alipayNotify(Map<String, String> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {e.printStackTrace();}
            params.put(name, valueStr);
        }
        String out_trade_no="";
        String cash="";
        String trade_status="";
        try {
            //商户订单号
            out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {e.printStackTrace();}

        try {
            cash = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {e.printStackTrace();}
        try {
            trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {e.printStackTrace();}
        try {//支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {e.printStackTrace();}

        //计算得出通知验证结果
        boolean verify_result = false;
        try {
            verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");
        } catch (AlipayApiException e) {e.printStackTrace();}

        if(verify_result){//验证成功
                if (trade_status.equals("TRADE_SUCCESS")||trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序
                try {
                    Map<String,String> orderParams = new HashMap<String,String>();
                    Order order=orderService.selectByOrderNo(out_trade_no);
                    if(order!=null){
                        if(order.getOrderStatus().equals("701")){
                            orderParams.put("userNoId",order.getUsernoId()+"");
                            orderParams.put("orderNo",out_trade_no);
                            orderParams.put("inter",order.getInter()+"");
                            orderParams.put("costInter",order.getCostInter()+"");
                            orderParams.put("cash",cash);
                        }
                    }
                    Response response1=payOrderService.payInter(orderParams,request);
                    return response1;
                }catch (Exception e){
                    return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"支付异常！",request);
                }
                //注意：
                //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            }else {
                    return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"订单未支付！",request);
                }
        }else{
            return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"支付参数异常！",request);
        }
    }
}
